"""
FastAPI应用主入口文件
"""
from fastapi import FastAPI, Request, Depends
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.trustedhost import TrustedHostMiddleware
from fastapi.responses import JSONResponse
from fastapi.staticfiles import StaticFiles
from starlette.responses import Response
from starlette.staticfiles import FileResponse
import time
import os

from starlette.responses import RedirectResponse

from core.config import settings
from core.database import create_tables, check_database_connection
from core.logging_config import get_logger, log_performance, log_api_request
from core.exceptions import setup_exception_handlers
from services.security_service import SecurityMiddleware

# 导入API路由
from api.auth import auth_router
from api.users import users_router, user_stats_router
from api.data_sources import data_sources_router
from api.analysis_tasks import analysis_tasks_router
from api.analysis_results_new import analysis_results_router
from api.petition_records import petition_records_router
from api.reports import reports_router
from api.system import system_router
from api.ai_services import ai_services_router
from api.llm_api import llm_router
from api.geo_analysis import geo_analysis_router
from api.regional_analysis import regional_analysis_router
from api.complaint_analysis import complaint_analysis_router
from api.sentiment_analysis import sentiment_analysis_router
from api.compliance_analysis import compliance_analysis_router
from api.duplicate_analysis import duplicate_analysis_router
from api.security import security_router
from api.web import web_router
from api.petition_ledger import router as petition_ledger_router
from api.prompt_templates import router as prompt_templates_router
from api.pollution_types import router as pollution_types_router
from api.pollution_types_debug import router as pollution_types_debug_router
from api.ai_analysis_config import ai_analysis_config_router
# from api.websocket import websocket_router  # 暂时注释，依赖已删除的统计服务
from services.service_manager import service_manager

# 获取日志记录器
logger = get_logger("petition_main")

"""创建FastAPI应用实例"""
app = FastAPI(
    title=settings.app_name,
    version=settings.app_version,
    description="基于大模型的智能信访分析平台后端服务",
    debug=settings.debug,
    docs_url="/docs" if settings.debug else None,
    redoc_url="/redoc" if settings.debug else None,
    openapi_url="/openapi.json" if settings.debug else None,
)

# 设置异常处理器
setup_exception_handlers(app)

# 配置CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.cors_origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 配置可信主机中间件
app.add_middleware(
    TrustedHostMiddleware,
    allowed_hosts=["*"] if settings.debug else ["localhost", "127.0.0.1"]
)

# 配置安全中间件
app.add_middleware(SecurityMiddleware)

# 请求日志中间件
@app.middleware("http")
async def log_requests(request: Request, call_next):
    """请求日志中间件"""
    start_time = time.time()
    
    # 记录请求信息
    logger.info(
        f"Request: {request.method} {request.url.path}",
        extra={
            "method": request.method,
            "path": request.url.path,
            "query_params": str(request.query_params),
            "client_host": request.client.host if request.client else "unknown"
        }
    )
    
    response = await call_next(request)
    
    # 记录响应信息
    process_time = time.time() - start_time
    logger.info(
        f"Response: {response.status_code} ({process_time:.3f}s)",
        extra={
            "status_code": response.status_code,
            "process_time": process_time,
            "method": request.method,
            "path": request.url.path
        }
    )
    
    return response

# 自定义静态文件服务类，添加缓存头
class CachedStaticFiles(StaticFiles):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
    
    async def get_response(self, path: str, scope) -> Response:
        response = await super().get_response(path, scope)
        
        # 为静态资源添加缓存头
        if response.status_code == 200:
            file_ext = path.split('.')[-1].lower() if '.' in path else ''
            
            # 根据文件类型设置不同的缓存时间
            if file_ext in ['css', 'js']:
                response.headers["Cache-Control"] = "public, max-age=31536000, immutable"  # 1年
            elif file_ext in ['png', 'jpg', 'jpeg', 'gif', 'svg', 'ico', 'webp']:
                response.headers["Cache-Control"] = "public, max-age=31536000, immutable"  # 1年
            elif file_ext in ['woff', 'woff2', 'ttf', 'eot', 'otf']:
                response.headers["Cache-Control"] = "public, max-age=31536000, immutable"  # 1年
            else:
                response.headers["Cache-Control"] = "public, max-age=86400"  # 1天
            
            # 添加简单的ETag支持（基于文件路径和修改时间）
            import hashlib
            etag_content = f"{path}_{int(time.time())}"
            response.headers["ETag"] = f'"{hashlib.md5(etag_content.encode()).hexdigest()}"'
        
        return response

# 静态文件服务
try:
    app.mount("/static", CachedStaticFiles(directory="static"), name="static")
except RuntimeError as e:
    logger.warning(f"静态文件目录不存在，跳过静态文件服务: {e}")


# 注册API路由
app.include_router(auth_router, prefix="/api/auth", tags=["认证"])
app.include_router(users_router, prefix="/api/users", tags=["用户管理"])
app.include_router(user_stats_router, tags=["用户统计"])  # 独立的用户统计路由，避免路由冲突
app.include_router(data_sources_router, prefix="/api/data-sources", tags=["数据源管理"])
app.include_router(ai_services_router, prefix="/api/ai-services", tags=["AI分析服务"])
app.include_router(llm_router, prefix="/api/llm", tags=["大模型分析"])
app.include_router(analysis_tasks_router, prefix="/api/analysis-tasks", tags=["分析任务"])
# app.include_router(analysis_results_old_router, prefix="/api/analysis-results", tags=["分析结果"])
app.include_router(analysis_results_router, prefix="/api/analysis-results-new", tags=["分析结果管理"])
app.include_router(petition_records_router, prefix="/api/petition-records", tags=["信访记录管理"])
app.include_router(geo_analysis_router, prefix="/api/geo-analysis", tags=["地理分析"])
app.include_router(reports_router, prefix="/api/reports", tags=["报告生成"])
app.include_router(system_router, prefix="/api/system", tags=["系统管理"])
app.include_router(security_router, prefix="/api/security", tags=["安全管理"])
app.include_router(prompt_templates_router, prefix="/api/prompts", tags=["提示词模板"])
app.include_router(pollution_types_router, prefix="/api/pollution-types", tags=["污染类型管理"])
app.include_router(pollution_types_debug_router, tags=["污染类型管理调试"])
app.include_router(ai_analysis_config_router, tags=["AI分析配置"])
app.include_router(regional_analysis_router, prefix="/api/regional-analysis", tags=["区域分析"])
app.include_router(complaint_analysis_router, prefix="/api/complaint-analysis", tags=["投诉类型分析"])
app.include_router(sentiment_analysis_router, prefix="/api/sentiment-analysis", tags=["情感分析"])
app.include_router(compliance_analysis_router, prefix="/api/compliance-analysis", tags=["规范性分析"])
app.include_router(duplicate_analysis_router, prefix="/api/duplicate-analysis", tags=["重复分析"])
app.include_router(petition_ledger_router, prefix="/api", tags=["信访台账"])

# 注册Web界面路由
app.include_router(web_router,prefix="/web", tags=["Web界面"])

# 注册WebSocket路由 - 暂时注释，依赖已删除的统计服务
# app.include_router(websocket_router)
logger.info("默认普通用户创建成功: user/user")

# 健康检查端点
@app.get("/health")
@log_performance("health_check")
async def health_check():
    """健康检查端点"""
    db_status = check_database_connection()

    return {
        "status": "healthy" if db_status else "unhealthy",
        "service": settings.app_name,
        "version": settings.app_version,
        "database": "connected" if db_status else "disconnected",
        "timestamp": time.time()
    }

# 根路径重定向到仪表板
@app.get("/", response_class=RedirectResponse)
async def root(request: Request):
    """根路径重定向到仪表板，带登录状态检查"""
    # 检查用户是否已登录
    from core.database import SessionLocal
    from core.auth import get_current_user_from_token
    
    # 尝试从Authorization头获取token
    auth_header = request.headers.get("Authorization")
    token = None
    
    if auth_header and auth_header.startswith("Bearer "):
        token = auth_header.split(" ")[1]
    else:
        # 尝试从cookie中获取
        token = request.cookies.get("auth_token")
    
    if token:
        try:
            db = SessionLocal()
            user = get_current_user_from_token(token, db)
            db.close()
            if user:
                # 已登录，直接跳转到dashboard
                return RedirectResponse(url="/web/analysis-results", status_code=302)
        except Exception:
            # token无效，继续到登录页面
            pass
    
    # 未登录，跳转到登录页面
    return RedirectResponse(url="/web/login", status_code=302)

# 应用启动事件
@app.on_event("startup")
async def startup_event():
    """应用启动事件"""
    logger.info(f"正在启动 {settings.app_name} v{settings.app_version}")
    logger.info(f"启动时间: {time.strftime('%Y-%m-%d %H:%M:%S')}")
    logger.info(f"工作目录: {os.getcwd()}")
    logger.info(f"Python版本: {os.sys.version}")
    
    # 创建数据库表
    try:
        logger.info("开始创建数据库表...")
        create_tables()
        logger.info("数据库表初始化完成")
    except Exception as e:
        logger.error(f"数据库表初始化失败: {e}")
    
    # 检查数据库连接
    logger.info("检查数据库连接...")
    if check_database_connection():
        logger.info("数据库连接正常")
        
        # 初始化认证数据
        try:
            logger.info("开始初始化认证数据...")
            from core.auth import init_auth_data
            from core.database import SessionLocal
            db = SessionLocal()
            init_auth_data(db)
            db.close()
            logger.info("认证数据初始化完成")
        except Exception as e:
            logger.error(f"认证数据初始化失败: {e}")
        
        # 启动AI服务工厂（可选，如果失败不会阻止应用启动）
        try:
            logger.info("开始注册AI服务...")
            from services.ai_analysis_services import register_ai_services
            register_ai_services()
            logger.info("AI服务注册完成")
            
            # 临时注释掉AI服务启动，避免阻塞
            logger.info("跳过AI服务启动，避免阻塞")
            # from services.ai_service_factory import ai_service_factory
            # start_results = await ai_service_factory.start_all_services()
            # successful_starts = sum(1 for success in start_results.values() if success)
            # logger.info(f"AI服务启动完成，{successful_starts} 个服务启动成功")
        except Exception as e:
            logger.warning(f"AI服务启动失败（非致命）: {e}")
        
        # 临时注释掉大模型服务管理器初始化，避免阻塞
        logger.info("跳过大模型服务管理器初始化，避免阻塞")
        # try:
        #     from services.llm_service import llm_service_manager
        #     # 测试大模型服务连接
        #     if settings.llm_api_key:
        #         health_check = await llm_service_manager.health_check()
        #         if health_check["healthy"]:
        #             logger.info(f"大模型服务连接正常: {health_check.get('provider', 'Unknown')}")
        #         else:
        #             logger.warning(f"大模型服务连接失败: {health_check.get('error', 'Unknown error')}")
        #     else:
        #         logger.info("未配置大模型API密钥，跳过大模型服务初始化")
        # except Exception as e:
        #     logger.warning(f"大模型服务初始化失败（非致命）: {e}")
        
        # 临时注释掉任务管理器启动，避免阻塞
        logger.info("跳过任务管理器启动，避免阻塞")
        # try:
        #     from services.task_manager import task_manager
        #     await task_manager.start()
        #     logger.info("任务管理器启动完成")
        # except Exception as e:
        #     logger.warning(f"任务管理器启动失败（非致命）: {e}")
    else:
        logger.error("数据库连接失败")
    
    logger.info(f"{settings.app_name} 启动完成")
    logger.info(f"启动完成时间: {time.strftime('%Y-%m-%d %H:%M:%S')}")
    logger.info(f"服务器地址: http://{settings.host}:{settings.port}")
    logger.info(f"本地访问地址：http://localhost:{settings.port}/web")
    logger.info(f"调试模式: {settings.debug}")
    logger.info(f"文档地址: http://{settings.host}:{settings.port}/docs" if settings.debug else "文档地址: 生产环境未启用")

# 应用关闭事件
@app.on_event("shutdown")
async def shutdown_event():
    """应用关闭事件"""
    logger.info(f"正在关闭 {settings.app_name}")
    
    # 停止任务管理器
    try:
        from services.task_manager import task_manager
        await task_manager.stop()
        logger.info("任务管理器已停止")
    except Exception as e:
        logger.error(f"任务管理器停止失败: {e}")
    
    # 停止AI服务工厂
    try:
        from services.ai_service_factory import ai_service_factory
        await ai_service_factory.stop_all_services()
        logger.info("AI服务已停止")
    except Exception as e:
        logger.error(f"AI服务停止失败: {e}")
    
    logger.info(f"{settings.app_name} 已关闭")




if __name__ == "__main__":
    import uvicorn
    uvicorn.run(
        "main:app",
        host=settings.host,
        port=settings.port,
        reload=settings.debug,
        log_level=settings.log_level.lower()
    )